package com.sayice.robotconflict.common.exception.handler;

import com.sayice.robotconflict.common.exception.AppException;
import com.sayice.robotconflict.common.exception.ErrorCode;
import com.sayice.robotconflict.common.result.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 异常处理
 *
 * @author shubing
 */
@Slf4j
@RestControllerAdvice
public class WebExceptionHandler {
    /**
     * 处理自定义异常
     */
    @ExceptionHandler(AppException.class)
    public ApiResult handleAppException(AppException e) {
        log.error(e.getClass().getSimpleName(), e);
        Integer errorCode = e.getErrorCode();
        return new ApiResult(errorCode == null ? ErrorCode.CODE_500 : errorCode, e.getLocalizedMessage());
    }
    
    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResult handleValidException(MethodArgumentNotValidException e) {
        log.error(e.getClass().getSimpleName(), e);
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        String msg = objectError == null ? "参数校验失败" : objectError.getDefaultMessage();
        return new ApiResult(ErrorCode.CODE_400, msg);
    }
    
    /**
     * 处理其他异常
     */
    @ExceptionHandler(Exception.class)
    public ApiResult handleException(Exception e) {
        log.error(e.getClass().getSimpleName(), e);
        return new ApiResult(ErrorCode.CODE_500, e.getLocalizedMessage());
    }
}
